<style>
    .ly-dashboard-echarts {
        width: 100%;
        height: 185px;
    }

</style>
<template>
    <div  v-loading="loading" style="width: 100%;">
        <e-chart
                ref="chart"
                :options="chartConfig"
                :auto-resize="true"
                :style="{'width': '100%','height':height+'px'}"
        ></e-chart>
        <div v-if="table">
            <div style="display: flex">
                <el-button @click="showTable=!showTable" type="text">{{showTable?'隐藏数据':'显示数据'}}</el-button>
                <div style="flex: 1"></div>
                <el-button @click="download" v-if="showTable" type="text">下载</el-button>
            </div>
            <table  class="ly-table ly-table-border ly-table-striped"
                    v-if="showTable&&chartConfig&&chartConfig.series&&chartConfig.xAxis">
                <thead>
                <tr>
                    <th>{{x_name}}</th>
                    <th v-for="item in chartConfig.series">
                        {{item.name}}
                    </th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="time in x_data">
                    <td>{{time}}</td>
                    <td v-for="(item,index) in chartConfig.series">
                        {{result[time]["i"+index]}}
                    </td>
                </tr>
                </tbody>
            </table>
        </div>

    </div>
</template>
<script>

    function dateTime(date,move){
        var begin_time=date.begin_time;
        var end_time=date.end_time;
        var date_format=date.date_format;
        var date_type=date.date_type;
        if(move){
            if(date_type==='today'){
                begin_time=begin_time - 24*60*60;
            }else if(date_type==='this_month'){
                begin_time=dayjs().add(-1,"M").startOf('month').unix();
            }
            else if(date_type==='this_week'){
                begin_time=dayjs().add(-1,"w").startOf('week').unix();
            } else{
                begin_time=date.begin_time*2 -date.end_time;
            }
            end_time = date.begin_time;
        }else{
            if(date_type==='today'){
                end_time=dayjs().endOf('day').unix()
            }
            else if(date_type==='this_week'){
                end_time=dayjs().endOf('week').unix()
            }
            else if(date_type==='this_month'){
                end_time=dayjs().endOf('month').unix()
            }
        }
        var ts=[];
        while(begin_time<end_time){
            if(date_format==='m'){
                var t=dayjs.unix(begin_time).format('YYYY-MM-DD HH:mm')
                ts.push(t);
                begin_time+=60;
            }
            if(date_format==='H'){
                var t=dayjs.unix(begin_time).format('YYYY-MM-DD HH:00')
                ts.push(t);
                begin_time+=60*60;
            }
            if(date_format==='D'){
                var t=dayjs.unix(begin_time).format('YYYY-MM-DD')
                ts.push(t);
                begin_time+=60*60*24;
            }
            if(date_format==='M'){
                var t=dayjs.unix(begin_time).format('YYYY-MM')
                ts.push(t);
                begin_time=dayjs.unix(begin_time).add(1,"M").unix();
            }
        }
        return ts;
    }

    //这里定义组件
    Rap.define([], function () {
        return {
            name: 'ly-chart',
            props:
                {
                    noGlobal:Boolean,
                    params: {
                        'default': function () {
                            return {}
                        }
                    },
                    name:{
                        'default': function () {
                            return ""
                        }
                    },
                    date: {
                        'default': function () {
                            return {}
                        }
                    },
                    //高度
                    height: {
                        'default': 310
                    },
                    //图标类型
                    type: {
                        'default': 'line'
                    },
                    //数据链接
                    link: {
                        'default': '',
                    },
                    //x 取值
                    key_x: {
                        'default': 'time'
                    },
                    //y 取值
                    key_y: {
                        'default': 'c'
                    },
                    //显示折现图的区域
                    area: {
                        default: false
                    },
                    direction:{
                        default: 'x'
                    },
                    //line 类型时背景色
                    color: {
                        default:function (){
                            if(Ly.chart&&Ly.chart.color){
                                return Ly.chart.color;
                            }
                            return ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'];
                        }
                    },
                    colorIndex:Number,
                    areaColor: {
                        default:function (){
                            return null;
                        }
                    },
                    /**
                     *  多条线配置到数组里
                     *  [{name: 'pv', link: "https://lyio.magcloud.net/statistics/site/pv"},
                     {name: 'vv', link: "https://lyio.magcloud.net/statistics/site/vv"},
                     {name: 'uv', link: "https://lyio.magcloud.net/statistics/site/uv"}]
                     */
                    items: {
                        'default': function () {
                            return [];
                        }
                    },
                    //显示底部数据 table
                    table:{
                        default:false
                    },
                    tableShow:{
                        default:false
                    },
                    x_name:{
                        default:"时间"
                    },
                    show:{
                        default:function (){
                            return {x:true,y:true}
                        }
                    },
                    compare:{
                        default:false
                    }
                },
            data: function () {

                return {
                    chart_id: 0,
                    loading: false,
                    chartConfig: null,
                    result: [],
                    showTable:false,
                    x_data:[],
                    global_params:Ly.chart.global_params
                }
            },
            created: function () {
                this.chart_id = this._uid;
                var loadDebounce = _.debounce(this.load, 200);
                this.loadDebounce = loadDebounce;
                loadDebounce();
                if(this.tableShow){
                    this.showTable=true;
                }
            },
            mounted () {
                window.addEventListener('resize', this.resize);
            },
            watch: {
                tableShow:function (){
                    this.showTable=this.tableShow;
                },
                params: {
                    deep: true,
                    handler: function () {
                        this.loadDebounce();
                    }
                },
                link: function (){
                    this.loadDebounce();
                },
                date: {
                    deep: true,
                    handler: function () {
                        this.loadDebounce();
                    }
                },
                global_params:{
                    deep: true,
                    handler: function () {
                        this.loadDebounce();
                    }
                }
            },
            init: function () {
            },
            beforeDestroy: function () {
                window.removeEventListener('resize', this.resize);
            },
            methods: {
                resize: function () {
                    this.$refs.chart.resize();
                },
                download:function (){
                    function doSave(value, type, name) {
                        var blob;
                        if (typeof window.Blob == "function") {
                            blob = new Blob([value], {type: type});
                        } else {
                            var BlobBuilder = window.BlobBuilder || window.MozBlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder;
                            var bb = new BlobBuilder();
                            bb.append(value);
                            blob = bb.getBlob(type);
                        }
                        var URL = window.URL || window.webkitURL;
                        var bloburl = URL.createObjectURL(blob);
                        var anchor = document.createElement("a");
                        if ('download' in anchor) {
                            anchor.style.visibility = "hidden";
                            anchor.href = bloburl;
                            anchor.download = name;
                            document.body.appendChild(anchor);
                            var evt = document.createEvent("MouseEvents");
                            evt.initEvent("click", true, true);
                            anchor.dispatchEvent(evt);
                            document.body.removeChild(anchor);
                        } else {
                            location.href = bloburl;
                        }
                    }
                    var text=this.x_name;
                    for (var i =0;i<this.chartConfig.series.length;i++){
                        var name= this.chartConfig.series[i].name;
                        text+=","+name;
                    }
                    text+="\n";
                    for (var i =0;i<this.x_data.length;i++){
                        var time=this.x_data[i];
                        text+= time;
                        for (var index =0;index<this.chartConfig.series.length;index++){
                            text+=","+this.result[time]["i"+index];
                        }
                        text+="\n";
                    }
                    doSave(text,'text/csv','数据.csv')
                },
                load: function () {
                    var me = this;
                    this.loading = true;
                    var color=this.color;
                    if(this.colorIndex){
                        color=[color[this.colorIndex]];
                    }
                    var chartConfig = {
                        tooltip: {
                            trigger: "axis",
                        },
                        color: color,
                        legend: {
                            data: [],
                            itemHeight: 1, // 设置高度
                            textStyle: {
                                color: "rgba(0, 0, 0, 0.45)"
                            },
                            formatter:function (text){
                                if(!me.compare){
                                    return  text;
                                }
                                var index=chartConfig.legend.data.indexOf(text);
                                if(me.date.date_type==='today'){
                                    return index===0?'今日':'昨日';
                                }
                                if(me.date.date_type==='this_week'){
                                    return index===0?'本周':'上周';
                                }
                                if(me.date.date_type==='last_week'){
                                    return index===0?'上周':'上上周';
                                }
                                if(me.date.date_type==='this_month'){
                                    return index===0?'本月':'上月';
                                }
                                if(me.date.date_type==='yesterday'){
                                    return index===0?'昨日':'前日';
                                }
                                return chartConfig.xAxis[index].data[0];
                            }
                        },
                        grid: {
                            containLabel: true,
                            left: 10,
                            right: 10,
                            bottom: 10,
                            top: 50,
                        },
                        xAxis: [{
                            type: me.direction==='x'?"category":"value",
                            data: [],
                            splitLine: {
                                show: false,
                            },
                            axisTick: {
                                show: this.show.x,
                            },
                            axisLabel: {
                                show: this.show.x,
                            },

                            axisLine: {
                                show: this.show.x,
                                lineStyle: {
                                    color: "rgba(0, 0, 0, 0.45)"
                                }
                            },
                        }],
                        yAxis: {
                            type: me.direction==='y'?"category":"value",
                            data: [],
                            axisTick: {
                                show: this.show.y,
                            },
                            min:function (value) {
                                var min = Number.parseInt(value.min-(value.max-value.min) *0.1);
                                if(min<0&&value.min>0){
                                    min=0;
                                }
                                return min;
                            },
                            axisLabel: {
                                show:this.show.y,
                            },
                            axisLine: {
                                show: this.show.y,
                                lineStyle: {
                                    color: "rgba(0, 0, 0, 0.45)"
                                },
                            },
                            splitLine: {
                                lineStyle: {
                                    color: "rgba(0, 0, 0, 0.05)"
                                },
                            },
                        },
                        series: [],
                    };

                    var items = me.items;
                    if (!items || items.length === 0) {
                        items = [{
                            name: me.name ? me.name : "数量",
                            link: this.link,
                            key_x: this.key_x,
                            key_y: this.key_y,
                        }];
                        if(me.compare){
                            var link=this.link;
                            if (link.indexOf('?') === -1) {
                                link += '?';
                            }else{
                                var end=link.substring(link.length-1,link.length);
                                if(end!=='?'&&end!=='&'){
                                    link+="&";
                                }
                            }
                            link+='move=1';
                            items.push({
                                name: me.name ? me.name : "数量",
                                link:link,
                                key_x: this.key_x,
                                key_y: this.key_y,
                            });
                            chartConfig.xAxis.push({
                                type: me.direction==='x'?"category":"value",
                                data: [],
                                show:false
                            });
                            items[1].name=items[1].name+' ';
                        }
                    }
                    var x_data = {};
                    var series = [];
                    var result = [];

                    function responseHandle(rs) {
                        var item = rs.config.item;
                        var serie = {
                            name: item.name,
                            type: me.type,
                            smooth: true,
                            symbolSize: 6,
                            showSymbol: false,
                            data: []
                        };
                        if (me.areaColor&&me.areaColor.length>item.index) {
                            serie.areaStyle = {
                                color: me.areaColor[item.index],
                            }
                        }else if(me.area){
                            serie.areaStyle = {}
                        }

                        var data = rs.data.data;
                        result.push(data);
                        var keys=[];
                        var vals=[];
                        for (var i = 0; i < data.length; i++) {
                            var it = data[i];
                            var key = it[item.key_x];
                            if (!x_data[key]) {
                                x_data[key] = {};
                            }
                            vals.push(it[item.key_y]);
                            var v_index = 'i' + item.index;
                            x_data[key][v_index] = it[item.key_y]
                            keys.push(key);
                        }
                        series.push(serie);
                        // if(me.compare){
                        //     chartConfig.xAxis[item.index].data = keys;
                        //     serie.data=vals;
                        //     serie.xAxisIndex=item.index;
                        //     if(item.index>0){
                        //         serie.lineStyle={};
                        //         serie.lineStyle.type='dotted';
                        //     }
                        // }
                    }

                    var promise = new Promise(function (r) {
                        r()
                    });
                    var names = [];
                    for (var i = 0; i < items.length; i++) {
                        (function () {
                            var item = items[i];
                            item.index = i;
                            if (!item.key_x) {
                                item.key_x = me.key_x;
                            }
                            if (!item.key_y) {
                                item.key_y = me.key_y;
                            }
                            names.push(item.name);
                            var link = item.link;
                            if (link.indexOf('?') === -1) {
                                link += '?';
                            }else{
                                var end=link.substring(link.length-1,link.length);
                                if(end!=='?'&&end!=='&'){
                                    link+="&";
                                }
                            }
                            for (var key in me.date) {
                                link += (key + "=" + me.date[key] + "&");
                            }

                            var params = me.params;
                            if(!me.noGlobal){
                                params = _.extend({},Ly.chart.global_params,me.params);
                            }
                            var load = axios.post(link,params ,{item: item});
                            promise = promise.then(function (rs) {
                                if (rs) {
                                    responseHandle(rs);
                                }
                                return load;
                            });
                        })();
                    }
                    promise = promise.then(function (rs) {
                        responseHandle(rs);
                        // if(me.compare&&chartConfig.xAxis[0].data.length!==chartConfig.xAxis[1].data.length){
                        //     var ts=[];
                        //     for(var i=0;i<=chartConfig.xAxis[1].data.length;i++){
                        //         var t= chartConfig.xAxis[1].data[i];
                        //         t=dayjs(t).format('HH:mm');
                        //         ts.push(t);
                        //     }
                        //     chartConfig.xAxis[0].data=ts;
                        //     chartConfig.xAxis[1].data=ts;
                        // }
                        var times = _.keys(x_data);
                        me.x_data=times;
                        if(items.length>1){
                            times = _.sortBy(times, function(v){ return Number(v) || v; });
                        }
                        if(me.direction==='y'){
                            var t=[];
                            for(var i=times.length-1;i>-1;i--){
                                t.push(times[i]);
                            }
                            times=t;
                            chartConfig.yAxis.data = times;
                        }else if(!me.compare){
                            chartConfig.xAxis[0].data = times;
                        }
                        if(!me.compare){
                            for (var i = 0; i < items.length; i++) {
                                var kk = [];
                                for (var j = 0; j < times.length; j++) {
                                    var time = times[j];
                                    var k = 'i' + i;
                                    var v = x_data[time][k];
                                    if (!v) {
                                        v = '';
                                    }
                                    kk.push(v);
                                }
                                series[i].data = kk;
                            }
                        }else{
                            var ts = dateTime(me.date);
                            var ts1 = dateTime(me.date,true);
                            var v0s=[]
                            var v1s=[]
                            var tsM=ts.length>ts1.length?ts1:ts;
                            var absCj=Math.abs(ts.length-ts1.length);
                            for(var i=0;i<absCj;i++){
                                tsM.push('-');
                            }
                            for(var i=0;i<ts.length;i++){
                                var d=x_data[ts[i]];
                                if(d){
                                    v0s.push(d['i0']);
                                }else{
                                    v0s.push('');
                                }
                            }
                            for(var i=0;i<ts1.length;i++){
                                var d=x_data[ts1[i]];
                                if(d){
                                    v1s.push(d['i1']);
                                }else{
                                    v1s.push('');
                                }
                            }
                            chartConfig.xAxis[0].data = ts;
                            series[0].data=v0s;
                            series[0].xAxisIndex=0;
                            chartConfig.xAxis[1].data = ts1;
                            series[1].data = v1s;
                            series[1].xAxisIndex=1;
                            series[1].lineStyle={};
                            series[1].lineStyle.type='dotted';

                        }
                        chartConfig.series = series;
                        if (names.length > 1) {
                            chartConfig.legend.data = names;
                        } else {
                            delete chartConfig.legend;
                        }
                        console.log(JSON.stringify(chartConfig));
                        me.chartConfig = chartConfig;
                        me.loading = false;
                        me.result = x_data;
                    }).catch(function () {
                        me.loading = false;
                    });
                }
            }
        }
    })
</script>
